package whisper.service.coder.ffmpeg;

import org.apache.commons.lang3.StringUtils;
import whisper.service.coder.Command;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by JT on 2018/5/7
 */
public class FfmpegCommand implements Command {

    private static final String KEY_MEDIA_SRC = "MEDIA_SOURCE";
    private static final String KEY_MEDIA_TARGET = "MEDIA_TARGET";
    private static final String KEY_COVER_IF_EXISTS = "COVER_IF_EXISTS";
    private static final String KEY_THREADS = "THREADS";

    private Map<String, String> arguments = new HashMap<>();
    private StringBuilder argumentBuilder;

    public FfmpegCommand(String utilPath, String src, String target) {
        this.arguments.put(KEY_MEDIA_SRC, src);
        this.arguments.put(KEY_MEDIA_TARGET, target);
        this.argumentBuilder = new StringBuilder(utilPath);
    }

    public FfmpegCommand coverIfExists() {
        this.arguments.put(KEY_COVER_IF_EXISTS, "-y");
        return this;
    }

    public FfmpegCommand threads(int threads) {
        this.arguments.put(KEY_THREADS, String.valueOf(threads));
        return this;
    }

    public FfmpegCommand addArgument(String value) {
        this.argumentBuilder.append(' ').append(value).append(' ');
        return this;
    }

    public FfmpegCommand addArgument(String key, String value) {
        this.argumentBuilder.append(' ').append(key).append(' ').append(value).append(' ');
        return this;
    }

    @Override
    public String builder() {

        /* -y 是否覆盖已存在文件 */
        String coverIfExists = this.arguments.get(KEY_COVER_IF_EXISTS);
        if (StringUtils.isNotBlank(coverIfExists)) {
            this.addArgument(coverIfExists);
        }

        /* -threads 指定线程 */
        String threads = this.arguments.get(KEY_THREADS);
        if (StringUtils.isNotBlank(threads)) {
            this.addArgument("-threads", threads);
        }

        /* 设置源路径、目标路径 */
        String srcPath = this.arguments.get(KEY_MEDIA_SRC);
        String targetPath = this.arguments.get(KEY_MEDIA_TARGET);
        if (StringUtils.isNotBlank(srcPath) && StringUtils.isNotBlank(targetPath)) {
            this.addArgument("-i", srcPath).addArgument(targetPath);
        } else {
            throw new RuntimeException("FFmpeg: Media source path or target path is empty or null!");
        }

        return this.argumentBuilder.toString();
    }
}
